#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import os.path
import sys

from dws.commons.log_utils import log
from common.util.check_utils import is_valid_id
from common.common import exter_attack
from common.const import SubJobStatusEnum
from dws.commons.const import RestoreProgressFileName
from dws.restore.parse_restore_job import ParseRestoreJobParam
from common.util.exec_utils import exec_overwrite_file, su_exec_rm_cmd


@exter_attack
def do_post_job(pid, main_task_id, sub_task_id):
    restore_job_param = ParseRestoreJobParam(pid)
    # 清理cache仓
    _, cache_path = restore_job_param.get_available_path()
    if cache_path:
        for temp_dir in os.listdir(cache_path):
            if not su_exec_rm_cmd(os.path.join(cache_path, temp_dir)):
                log.error(f"Fail to delete dir {os.path.join(cache_path, temp_dir)}."
                          f"main task {main_task_id}, subtask {sub_task_id}")
                continue
    # 组装进度
    progress_dict = {
        "taskId": main_task_id, "subTaskId": sub_task_id, "taskStatus": SubJobStatusEnum.COMPLETED,
        "progress": 100, "dataSize": 0, "speed": 0
    }
    progress_file = os.path.join(cache_path,
                                 f"{RestoreProgressFileName.POST_JOB_PROGRESS}{restore_job_param.get_copy_id()}")
    progress_file = os.path.realpath(progress_file)
    try:
        exec_overwrite_file(progress_file, progress_dict)
    except Exception as e:
        log.error(f"Write post job progress failed for {e}. main task {main_task_id}, subtask {sub_task_id}")
    log.debug(f"Do post job finish")


if __name__ == "__main__":
    if len(sys.argv) < 4:
        log.error("Not enough input parameters.")
        sys.exit(1)
    pid_args = sys.argv[1]
    main_task_id_args = sys.argv[2]
    sub_task_id_args = sys.argv[3]

    if not is_valid_id(pid_args):
        log.warn(f"pid is invalid")
        sys.exit(1)

    if not is_valid_id(main_task_id_args):
        log.warn(f"main_task_id_args is invalid")
        sys.exit(1)

    if not is_valid_id(sub_task_id_args):
        log.warn(f"sub_task_id_args is invalid")
        sys.exit(1)

    log.info(f"Start to execute restore post job. Main task {main_task_id_args}, subtask {sub_task_id_args}")
    do_post_job(pid_args, main_task_id_args, sub_task_id_args)
